/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainGui.java
 *
 * Created on 03.02.2011., 22.40.52
 */
package gui;

import java.awt.AWTException;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.metal.OceanTheme;
import niti.Provera;
import util.Skripte;

/**
 *
 * @author shone
 */
public class MainGui extends javax.swing.JFrame {

    public MainGui(String adresa, int port, int intervalSec) {
        setLookAndFeel();
        initComponents();
        sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");

        try {
            setupTray();
        } catch (AWTException ex) {
            Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
        }

        cekanjeSkripte = 30000;
        proveraInterval = 1000 * intervalSec;
        proveraAdresa = adresa;
        proveraPort = port;
        String msg = "Pocetni parametre provere:"
                + "\nadresa = " + proveraAdresa
                + "\nport = " + proveraPort
                + "\ninterval = " + intervalSec;
        dodajInformaciju(msg);

        skripte = new Skripte();
        File[] skFiles = skripte.getSkripte();
        if(skFiles != null && skFiles.length > 0) {
            msg = "Ucitane skripte:";
            for(int i = 0; i < skFiles.length; i++) {
                msg += "\n" + skFiles[i].getName();
            }
            dodajInformaciju(msg);
        } else {
            dodajInformaciju("Ni jedna skripta nije ucitana!");
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        trayPopup = new java.awt.PopupMenu();
        jmiShow = new java.awt.MenuItem();
        jmiStart = new java.awt.MenuItem();
        jmiStop = new java.awt.MenuItem();
        jmiSettings = new java.awt.MenuItem();
        jmiAbout = new java.awt.MenuItem();
        jmiExit = new java.awt.MenuItem();
        jPanel = new javax.swing.JPanel();
        jScrollPane = new javax.swing.JScrollPane();
        jTextArea = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jlStatus = new javax.swing.JLabel();
        jToolBar1 = new javax.swing.JToolBar();
        jbStart = new javax.swing.JButton();
        jbStop = new javax.swing.JButton();
        jbSettings = new javax.swing.JButton();
        jbAbout = new javax.swing.JButton();
        jbExit = new javax.swing.JButton();

        trayPopup.setLabel("popupMenu1");

        jmiShow.setLabel("Pokazi prozor");
        jmiShow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmiShowActionPerformed(evt);
            }
        });
        trayPopup.add(jmiShow);

        jmiStart.setLabel("Start");
        jmiStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmiStartActionPerformed(evt);
            }
        });
        trayPopup.add(jmiStart);

        jmiStop.setLabel("Stop");
        trayPopup.add(jmiStop);

        jmiSettings.setLabel("Podesavanja");
        jmiSettings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmiSettingsActionPerformed(evt);
            }
        });
        trayPopup.add(jmiSettings);

        jmiAbout.setLabel("O programu");
        jmiAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmiAboutActionPerformed(evt);
            }
        });
        trayPopup.add(jmiAbout);

        jmiExit.setLabel("Izlaz");
        jmiExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmiExitActionPerformed(evt);
            }
        });
        trayPopup.add(jmiExit);

        setTitle("ReConnector");
        setBackground(new java.awt.Color(255, 255, 255));
        setResizable(false);

        jScrollPane.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), " Output "));

        jTextArea.setColumns(20);
        jTextArea.setEditable(false);
        jTextArea.setLineWrap(true);
        jTextArea.setRows(5);
        jTextArea.setWrapStyleWord(true);
        jScrollPane.setViewportView(jTextArea);

        jLabel1.setText("Status:");

        jlStatus.setText("offline");

        javax.swing.GroupLayout jPanelLayout = new javax.swing.GroupLayout(jPanel);
        jPanel.setLayout(jPanelLayout);
        jPanelLayout.setHorizontalGroup(
            jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(jPanelLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(20, 20, 20)
                        .addComponent(jlStatus)))
                .addContainerGap())
        );
        jPanelLayout.setVerticalGroup(
            jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jlStatus))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                .addContainerGap())
        );

        jToolBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jbStart.setText("Start");
        jbStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbStartActionPerformed(evt);
            }
        });
        jToolBar1.add(jbStart);

        jbStop.setText("Stop");
        jbStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbStopActionPerformed(evt);
            }
        });
        jToolBar1.add(jbStop);

        jbSettings.setText("Podesavanja");
        jbSettings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSettingsActionPerformed(evt);
            }
        });
        jToolBar1.add(jbSettings);

        jbAbout.setText("O programu");
        jbAbout.setFocusable(false);
        jbAbout.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbAbout.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAboutActionPerformed(evt);
            }
        });
        jToolBar1.add(jbAbout);

        jbExit.setText("Izlaz");
        jbExit.setFocusable(false);
        jbExit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbExit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbExitActionPerformed(evt);
            }
        });
        jToolBar1.add(jbExit);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSettingsActionPerformed
        settings();
    }//GEN-LAST:event_jbSettingsActionPerformed

    private void jbStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbStartActionPerformed
        start();
    }//GEN-LAST:event_jbStartActionPerformed

    private void jbStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbStopActionPerformed
        stop();
    }//GEN-LAST:event_jbStopActionPerformed

    private void jmiExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiExitActionPerformed
        exit();
}//GEN-LAST:event_jmiExitActionPerformed

    private void jmiShowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiShowActionPerformed
        this.setVisible(true);
    }//GEN-LAST:event_jmiShowActionPerformed

    private void jbExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExitActionPerformed
        exit();
    }//GEN-LAST:event_jbExitActionPerformed

    private void jbAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAboutActionPerformed
        showAbout();
    }//GEN-LAST:event_jbAboutActionPerformed

    private void jmiStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiStartActionPerformed
        start();
    }//GEN-LAST:event_jmiStartActionPerformed

    private void jmiSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiSettingsActionPerformed
        settings();
    }//GEN-LAST:event_jmiSettingsActionPerformed

    private void jmiAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiAboutActionPerformed
        showAbout();
    }//GEN-LAST:event_jmiAboutActionPerformed

    public void dodajInformaciju(String inf) {
        String timeStamp = "[" + sdf.format(new Date()) + "] ";
        String str = jTextArea.getText();
        str += timeStamp + inf + "\n";
        jTextArea.setText(str);
    }

    public void setStatus(String status) {
        jlStatus.setText(status);
    }

    private void setupTray() throws AWTException {
        if (!SystemTray.isSupported()) {
            return;
        }
        ImageIcon icon = new ImageIcon(getClass().getResource("/trayIcon/bittorrent.png"));
        TrayIcon trayIcon = new TrayIcon(icon.getImage());
        trayIcon.setPopupMenu(trayPopup);
        SystemTray sysTray = SystemTray.getSystemTray();
        sysTray.add(trayIcon);
    }

    private void setLookAndFeel() {
        try {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
            MetalLookAndFeel.setCurrentTheme(new OceanTheme());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void exit() {
        if (nitProvere != null) {
            nitProvere.interrupt();
            nitProvere = null;
        }

        System.exit(0);
    }

    private void showAbout() {
        JOptionPane.showMessageDialog(this, About.aboutTxt, "O programu", JOptionPane.INFORMATION_MESSAGE);
    }
    private String proveraAdresa;
    private int proveraPort;
    private long proveraInterval;
    private long cekanjeSkripte;
    private Provera nitProvere;
    private Skripte skripte;
    private SimpleDateFormat sdf;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel;
    private javax.swing.JScrollPane jScrollPane;
    private javax.swing.JTextArea jTextArea;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton jbAbout;
    private javax.swing.JButton jbExit;
    private javax.swing.JButton jbSettings;
    private javax.swing.JButton jbStart;
    private javax.swing.JButton jbStop;
    private javax.swing.JLabel jlStatus;
    private java.awt.MenuItem jmiAbout;
    private java.awt.MenuItem jmiExit;
    private java.awt.MenuItem jmiSettings;
    private java.awt.MenuItem jmiShow;
    private java.awt.MenuItem jmiStart;
    private java.awt.MenuItem jmiStop;
    private java.awt.PopupMenu trayPopup;
    // End of variables declaration//GEN-END:variables

    private void stop() {
        if (nitProvere == null) {
            return;
        }

        nitProvere.interrupt();
        nitProvere = null;
        dodajInformaciju("PREKIDAM PROVERU");
    }

    private void start() {
        if (nitProvere != null) {
            return;
        }

        nitProvere = new Provera(cekanjeSkripte, proveraInterval, proveraAdresa, proveraPort, this, skripte);
        nitProvere.pocniProvere();
    }

    private void settings() {
        SettingsDialog sd = new SettingsDialog(this, true, proveraInterval / 1000, proveraAdresa, proveraPort);
        int ret = sd.showDialog();

        if (ret == SettingsDialog.ret_ok) {
            proveraAdresa = sd.getAdresaProvere();
            proveraInterval = sd.getIntervalProvereSec() * 1000;
            proveraPort = sd.getPortProvere();
            String msg = "Postavljam parametre provere:"
                    + "\nadresa = " + proveraAdresa
                    + "\nport = " + proveraPort
                    + "\ninterval = " + sd.getIntervalProvereSec();
            dodajInformaciju(msg);
        }
    }
}
